package com.zh.common.view.web

import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.webkit.SslErrorHandler
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AlertDialog
import com.blankj.utilcode.util.LogUtils

open class IWebViewClient(
    private val iWebView: WebView, private val onMeasure: () -> Unit
) : WebViewClient() {

    var mMyWebViewClient: IWebView.MyWebViewClient? = null

    override fun onPageFinished(view: WebView, url: String) {
        super.onPageFinished(view, url)
        onMeasure.invoke()
        mMyWebViewClient?.onPageFinished(view, url)
    }

    override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
        super.onPageStarted(view, url, favicon)
        mMyWebViewClient?.onPageStarted(view, url, favicon)
    }

    override fun shouldOverrideUrlLoading(
        view: WebView?, request: WebResourceRequest?
    ): Boolean {
        return if (mMyWebViewClient == null) {
            super.shouldOverrideUrlLoading(view, request)
        } else {
            val load = mMyWebViewClient!!.shouldOverrideUrlLoading(view, request)
            if (!load) {
                super.shouldOverrideUrlLoading(view, request)
            } else {
                true
            }
        }
    }

    override fun onReceivedError(
        view: WebView?,
        request: WebResourceRequest?,
        error: WebResourceError?
    ) {
        super.onReceivedError(view, request, error)
        LogUtils.e(
            request?.url,
            error?.errorCode,
            error?.description,
        )
    }

    override fun onReceivedHttpError(
        view: WebView?,
        request: WebResourceRequest?,
        errorResponse: WebResourceResponse?
    ) {
        super.onReceivedHttpError(view, request, errorResponse)
        LogUtils.e(
            request?.url,
            errorResponse?.statusCode,
        )
    }

    override fun onReceivedSslError(
        view: WebView,
        handler: SslErrorHandler,
        error: SslError
    ) {
        LogUtils.e(
            error.url,
            error.primaryError,
        )
        mMyWebViewClient?.onReceivedSslError(view, handler, error)
        if (error.primaryError == SslError.SSL_UNTRUSTED ||
            error.primaryError == SslError.SSL_INVALID
        ) {//提示框
            // 显示警告提示用户不要继续浏览
            val builder = AlertDialog.Builder(iWebView.context)
            builder.setTitle("安全警告")
            builder.setMessage("您正在访问的网页安全证书存在问题，确定继续吗？")
            builder.setPositiveButton(
                "继续"
            ) { dialog, which -> // 用户选择继续浏览
                handler.proceed()
            }
            builder.setNegativeButton(
                "取消"
            ) { dialog, which -> // 用户选择取消浏览
                handler.cancel()
            }
            builder.create().show()
        } else {
            handler.cancel()
        }
    }

    override fun shouldInterceptRequest(
        view: WebView?, request: WebResourceRequest
    ): WebResourceResponse? {
        val response = super.shouldInterceptRequest(view, request)
        insertOrigin(response)
        return response
    }

    override fun shouldInterceptRequest(
        view: WebView?,
        url: String?
    ): WebResourceResponse? {
        val response = super.shouldInterceptRequest(view, url)
        insertOrigin(response)
        return response
    }

    private fun insertOrigin(resourceResponse: WebResourceResponse?) {
        if (resourceResponse != null) {
            var headersRep: MutableMap<String?, String?>? = java.util.HashMap()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                headersRep = resourceResponse.responseHeaders
            }
            if (headersRep != null) {
                if (!headersRep.containsKey("Access-Control-Allow-Origin")) {
                    headersRep["Access-Control-Allow-Origin"] = "*"
                }
                if (!headersRep.containsKey("Access-Control-Allow-Credentials")) {
                    headersRep["Access-Control-Allow-Credentials"] = "true"
                }
                if (!headersRep.containsKey("Access-Control-Max-Age")) {
                    headersRep["Access-Control-Max-Age"] = "1800"
                }
                if (!headersRep.containsKey("Access-Control-Allow-Methods")) {
                    headersRep["Access-Control-Allow-Methods"] =
                        "GET,HEAD,OPTIONS,POST,PUT"
                }
                if (!headersRep.containsKey("Access-Control-Allow-Headers")) {
                    headersRep["Access-Control-Allow-Headers"] = "*"
                }
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                resourceResponse.responseHeaders = headersRep
            }
        }
    }
}